$(function()
{
	//加载树
	departmentTree();
	//绑定事件
	$("#btnSubmit").bind('click',function()
	{
		submitData();
	});
	opertype = '';
	if(''!=$("#vdi_id").val() && null != $("#vdi_id").val())
	{
		opertype = 'modify';
	}
	else
	{
		opertype = 'create';
	}
	
	// 绑定vdiIP事件， 查看是否有重复的IP.
	$("#ip").blur(function() {
		if(opertype == 'modify')//修改时取消校验
		{
			return;
		}
		$("input").removeClass("validate-input-error");
		$(".validate-tooltip").css("display", "none");
		var ip_base_temp = $("#ip").val().trim();
		
		if(ip_base_temp == '') {
			$("#ip").addClass("validate-input-error").parent().
			find(".validate-tooltip").css("display", "block").text("IP不能为空.");			
			return;
		}
		
		if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(ip_base_temp)) {
			$("#ip").addClass("validate-input-error").parent().
			find(".validate-tooltip").css({"display":"block","max-width":"160px"}).text("example：192.168.168.168");			
			openAlert("IP不符合规则，请重新填写!");
			return;
		}
		
		$.ajax({
			url : BASE_PATH+"/vdiManagement/checkVdiIP.do",
			type : "post",
			datatype : "json",
			data : {ip : $("#ip").val().trim()},
			success : function(data) {
				if(!data.result) {
					$("#ip").focus();
					openAlert("IP不能重复， 请重新设置IP.");
				}
				else {
				}
			},
			error : function(e) {
				console.debug("error ocurred when check ip duplicate", e);
			}
		});
	});
	
	
	// 绑定LoginName事件， 查看是否有重复的LoginName.
	$("#loginName").blur(function() {
		$("input").removeClass("validate-input-error");
		$(".validate-tooltip").css("display", "none");
		var ip_base_temp = $("#loginName").val().trim();

		$.ajax({
			url : BASE_PATH+"/vdiManagement/checkLoginName.do",
			type : "post",
			datatype : "json",
			data : {loginName : $("#loginName").val().trim()},
			success : function(data) {
				if(!data.result) {
					$("#loginName").focus();
					openAlert("loginName不能重复， 请重新设置loginName.");
				}
				else {
				}
			},
			error : function(e) {
				console.debug("error ocurred when check LoginName duplicate", e);
			}
		});
	});
});
/**
 * 弹出选择用户模态窗口，添加用户
 */
function newUser()
{
	popUpPanelVdi(BASE_PATH+"/vdiManagement/addUserForGroup_sitemesh_popup.do",1000,650);
}
var ids = new Array();//存储id信息
var nameArr = new Array();
var modifyUser = false;
/**
 * 将子窗口床底过来的参数进行设置，显示为ReadOnly形式
 */
function setUserToForm(){
	var selectVal = document.getElementById('selected');
	var checkUser = '';

	if(selectVal.getElementsByTagName("span") != null)
	{
		selectVal.innerHTML = "";
	}
	
	for(var i = 0; i < ids.length ; i++)
	{
		var spanTag = document.createElement("span"); 
	    spanTag.className = "dynamicSpan";    
	    spanTag.innerHTML = nameArr[i] + " / " + ids[i] + " ";
	    checkUser += ids[i] + ',';
	    document.getElementById('selected').appendChild(spanTag); 
	}
	if(($("#userName").val()+ ',') != checkUser )//判断是否做了修改
	{
		modifyUser = true;
	}
}

var vdiArray = new Array();

function newSystem()
{
	popUpPanelVdi(BASE_PATH+"/vdiSystemInfo/vdiSystemInfoDisplay_sitemesh_popup.do",1000,650);
	setSystemToForm();
}

function popUpPanelVdi(url,w,h)
{
	var left = (window.screen.width-w)/2;
	var right = (window.screen.hwight-h)/2;
	var windowPara = "dialogHeight: "+h+"px;dialogWidth:"+w+"px;dialogTop:"+top+"px;dialogLeft:"+left+"px;";
	return window.showModalDialog(url,"",windowPara);
}
var modifySystem = false;
/**
 * 将子窗口床底过来的参数进行设置，显示为ReadOnly形式
 */
function setSystemToForm(){
	var selectVal = document.getElementById('selectedSys');
	var checkSystem = '';
	if(opertype == 'modify' && vdiArray == undefined)
	{
		return;
	}
	if(selectVal.getElementsByTagName("span") != null)
	{
		selectVal.innerHTML = "";
	}
	
	for(var i = 0; i < vdiArray[0][1].length ; i++)
	{
		var spanTag = document.createElement("span"); 
	    spanTag.className = "dynamicSpan";    
	    spanTag.innerHTML = vdiArray[0][1][i] ;
	    checkSystem += vdiArray[0][0][i] + ',';
	    document.getElementById('selectedSys').appendChild(spanTag); 
	}
	if(($("#system").val()+ ',') != checkSystem )
	{
		modifySystem = true;
	}
}

/**
 * 加载树和树的点击事件
 */
function departmentTree()
{
	var setting = 
	{
			view: 
			{
				dblClickExpand: false
			},
			
			data: 
			{
				
				key: 
				{
					title:"titleTip"
				},
				
				simpleData: 
				{
					enable: true
				}
			},
			
			callback:
			{
				beforeClick: beforeClick,
				onClick: onClick
			}
		};

	var zNodes = '[';
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/vdiManagement/queryDepts.do',
        dataType:"json",
        data:
        {
        	
        },
        
        success:function(data,textStatus)
        {
        	
        	for( var i = 0; i < data.length; i++ )
        	{
        		zNodes += '{id:"' + convertSpecialChar(data[i].deptId) + '",';
        		zNodes += 'pId:"' + convertSpecialChar(data[i].parentId) + '",';
        		zNodes += 'name:"' + convertSpecialChar( data[i].deptName ) + '",';
        		zNodes += 'titleTip:"' + convertSpecialChar( data[i].deptName ) + '",';
        		
        		if(opertype == 'modify' && $("#dept_id").val().trim() == data[i].deptId)
    			{
        			$("#dept_name").val(data[i].deptName);
    			}
        		
        		if( data[i].deptDesc == null )
        		{
            		zNodes += 'deptDesc:"",';
        		} 
        		else 
        		{
            		zNodes += 'deptDesc:"' + convertSpecialChar( data[i].deptDesc ) + '",';
        		}
        		zNodes += 'isLeaf:"' + data[i].isLeaf + '",';
        		zNodes += 'open:true}';
        		
        		if( i != (data.length - 1) )
        		{
        			zNodes += ',';
        		}
        	}
        	zNodes += ']';
    		// 加载树
    		$.fn.zTree.init($("#departmentTree"), setting, eval(zNodes));
    		//选中已有部门
    		var chooseId=$("#dept_id").val();
    		deptIsChoosed(chooseId);
        },
        
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	});
	
}
/**
 * 让已被选的部门在树中处于被选中状态
 * @param id 所选部门的id 
 */
function deptIsChoosed(id)
{
	var zTree = $.fn.zTree.getZTreeObj("departmentTree");
	var node = zTree.getNodeByParam("id",id,null);
	zTree.selectNode(node);
}

/**
 * 树点击前事件
 * @param treeId 树id
 * @param treeNode 树节点对象
 * @returns check 返回被选节点是否可选
 */
function beforeClick(treeId, treeNode) 
{
	var check = (treeNode && !treeNode.isParent);
	if (!check) openAlert("请选择具体部门！");
	return check;
	
}

/**
 * 树单击事件
 * @param e js的event对象
 * @param treeId 树id
 * @param treeNode 树节点对象
 */
function onClick(e, treeId, treeNode) 
{
	var zTree = $.fn.zTree.getZTreeObj("departmentTree"),
		nodes = zTree.getSelectedNodes(),
		v = "",
		id = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	
	for (var i=0, l=nodes.length; i<l; i++) 
	{
		v += nodes[i].name + ",";
		id += nodes[i].id + ",";
	}
	
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	
	if (id.length >0 ) id = id.substring(0,id.length-1);
	
	var cityObj = $("#dept_name");
	cityObj.attr("value", v);
	var deptId = $("#dept_id");
	deptId.attr("value",id);
	hideMenu();
	
}

/**
 * 显示树
 */
function showMenu() 
{
	
	var cityObj = $("#dept_name");
	var cityOffset = $("#dept_name").offset();
	$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top 
		+ cityObj.outerHeight() + "px"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
	
}

/**
 * 隐藏树
 */
function hideMenu() 
{
	
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
	
}

/**
 * 判断是否隐藏树
 * @param event 事件源
 */
function onBodyDown(event)
{
	
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" 
		|| $(event.target).parents("#menuContent").length>0)) 
	{
		hideMenu();
	}
	
}

/**
 * submit 提交
 */
function submitData()
{
	var ip_base_temp = $("#ip").val().trim();
	if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(ip_base_temp)) {
		openAlert("IP不符合规则，请重新填写!");
		return;
	}
	if(($("#ip").val().trim()==""||$("#ip").val().trim()==null)||($("#ip").val().trim()=="#"))
	{
		openAlert("IP不能为空，请填写!");
		return false;
	}
	if(($("#loginName").val().trim()==""||$("#loginName").val().trim()==null)||($("#loginName").val().trim()=="#"))
	{
		openAlert("登录名不能为空，请填写!");
		return false;
	}
	if(($("#password").val().trim()==""||$("#password").val().trim()==null)||($("#password").val().trim()=="#"))
	{
		openAlert("密码不能为空，请填写!");
		return false;
	}
	
	var systemIds='',systemNames='',userNames='',cnNames='';
	
	var vdi_id = $("#vdi_id").val();
	if(undefined == vdiArray || vdiArray.length == 0)
	{
		systemIds = $("#system").val();
	}
	else
	{
		for(var i =0;i < vdiArray[0][0].length; i ++)
		{
			systemIds += vdiArray[0][0][i] +",";
			if(modifySystem)
			{
				systemNames += vdiArray[0][1][i] +",";
			}
		}
	}
	
	if(ids.length == 0)
	{
		userNames = $("#userName").val();
	}
	else
	{
		for(var i =0;i < ids.length; i ++)
		{
			userNames += ids[i] +",";
			if(modifyUser)
			{
				cnNames += nameArr[i] + ",";
			}
		}
	}
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/vdiManagement/addOrUpdateVDI.do',
        dataType:"json",
		data:
		{
			"id"                :   $("#vdi_id").val().trim(),
			"ip" 		        : 	$("#ip").val().trim(),
			"loginName"  		: 	$("#loginName").val().trim(),
			"password"    	    :	$("#password").val().trim(),
			"computerName"		:	$("#computerName").val().trim(),
			"dishSpace"			:	$("#dishSpace").val().trim(),
			"freeSpace"			:	$("#freeSpace").val().trim(),
			"department"		:	$("#dept_id").val().trim(),
			"system"			:	systemIds,
			"systemName"		:	systemNames,
			"userName"			:	userNames,
			"cnName"			:	cnNames,
			"remark"			:	$("#remark").val().trim(),
			"opertype"          :   opertype
		},
		success : function(data) 
		{
			var datas = data.split(",");
			if(datas[0] =='success') { 
             if(opertype == "create") {
            	 openAlert('保存成功',function(){
            		 backToTab(datas[1]);
            	 }); 
             }
             else {
            	 openAlert("修改成功",function(){
            		 backToTab(datas[1]);
            	 });
             }
			}
			else
			{
				openAlert(data);
			}
			
		},
		
		error:function(e)
		{
			openAlert('操作失败！错误信息：<div>'+e.responseText+"</div>");
		}
	});
}

/**
 * 返回查询页
 */
function backToCurrentPage()
{
	window.parent.location.href = BASE_PATH + "/vdiManagement/vdiInfoList.do";
}

/**
 * 返回当前页
 */
function backToTab(vdiId)
{
//	window.parent.location.href = BASE_PATH + "/vdiManagement/toVDIInfoTab.do?vdiId="+vdiId;
	window.parent.refreshPage(vdiId);
}